package b;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-05-29
 * Time: 14:04
 */
public class BinarySearchTree implements IList {
    //使用内部类定义一个节点
    static class TreeNode{
        public int val ;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val) {
            this.val = val;
        }

    }
    public TreeNode root;

    public void insert(int val) {
        TreeNode node = new TreeNode(val);
        if(root == null){
            root =node;
            return;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null){
            if(cur.val < val) {
                parent = cur;
                cur = cur.right;
            }else if(cur.val > val){
                parent = cur;
                cur =cur.left;
            }else {
                //插入元素已经存在,无法插入,直接返回
                return;
            }
        }
        if(parent.val < val){
            parent.right = node;
        }else{
            parent.left = node;
        }

    }

    public int search(int val){
        if(root == null){
            return -1;
        }
        int count = 0;//计数器
        TreeNode cur = root;
        while(cur != null){
            if(cur.val < val){
                cur = cur.right;
                count++;
            }else if(cur.val > val){
                cur = cur.left;
                count++;
            }else {
                count++;
                return count;
            }
        }
        return -1 ;//没找到返回-1

    }

}
